package com.sloth.service.impl;

import com.alibaba.fastjson.JSON;
import com.sloth.pojo.Myorder;
import com.sloth.service.MyOrderService;
import com.sloth.util.RabbitMQConfiguration;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import com.rabbitmq.client.Channel;

/**
 * @author lai
 * @time 2021/11/2 9:47
 */

/**
 * 订单失效监听器
 */
@Component
public class MyOrderFailureListener {

    @Autowired
    private MyOrderService myOrderService;

    //    private static final Logger logger =  LoggerFactory.getLogger(MyOrderFailureListener.class);
    @RabbitListener( queues = RabbitMQConfiguration.deadQueueOrder )
    public void process(String myOrderString, Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {

        System.out.println("消费该消息队列");
        System.out.println("message");
        System.out.println(message);
        System.out.println("headers");
        System.out.println(headers);
        System.out.println("channel");
        System.out.println(channel);
//        logger.info("【订单号】 - [{}]",  order);

        // 将 String 类型的信息  转换为 Myorder 类型
        Myorder myorder = JSON.parseObject(myOrderString,Myorder.class);
        System.out.println(myorder);

        // 判断订单是否已经支付，如果支付则；否则，取消订单（逻辑代码省略)
        Myorder newMyorder = myOrderService.getMyOrderByMyOrderID(myorder.getOrderId());

        // 如果订单已经付款，不进行更改
        if (newMyorder.getOrderStates() == 1){  // 已付款
            System.out.println("订单为已支付状态");
        }

        // 如果订单没有付款，将订单状态改为未支付状态
        if (newMyorder.getOrderStates() == 0){  // 未支付
            System.out.println("订单为未支付状态");
            newMyorder.setOrderStates(-1);
            myOrderService.updateMyOrderStatue(newMyorder);  // 修改订单状态为 已取消
            System.out.println("订单状态已修改");
        }

        // 有时间的话，将订单中对订单状态为未支付的订单，
        // 重新三次放入队列中，因为可能存在网络原因或者支付原因导致支付成功，
        // 状态还未来得及进行修改而导致数据的丢失，
        // 因为在一般的工作中都不会设置消息重回队列中，所以就不进行设置了

        // 手动ack
//        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        // 手动签收
//        channel.basicAck(deliveryTag, false);
        System.out.println("执行结束....");

    }

}